﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using CounterServerModel;
using CounterServerModel.Authentication;

namespace SmartCounters
{
	public partial class MainTemplate : System.Web.UI.MasterPage
	{
		public const eUserPermissions k_GuestPageFilter = eUserPermissions.None;
		public const eUserPermissions k_AdminPageFilter = eUserPermissions.All;
		public const eUserPermissions k_UserPageFilter = eUserPermissions.ReadAssociatedAccountInfo |
			eUserPermissions.ReadOwnUserInfo |
			eUserPermissions.ReadOwnBill;
		
		
		public const string k_CurrentLoggedInUserSessionKey = "currentLoggedInUser";
		public static string k_CurrentAuthenticatedUserSessionKey = "currentAuthenticatedUser";

		public eUserPermissions m_PagePermissionFilter;
		
		public UserInfo LoggedInUser
		{
			get { return Session[k_CurrentLoggedInUserSessionKey] as UserInfo; }
		}
		public AuthenticatedUserCredentials AuthenticatedLoggedInUserCredentials
		{
			get { return Session[k_CurrentAuthenticatedUserSessionKey] as AuthenticatedUserCredentials; }
		}

		private bool showHeader = true;
		public bool ShowHeader
		{
			get { return showHeader; }
			set { showHeader = value; }
		}

		private void checkPermissionFilter()
		{
			if (LoggedInUser == null)
			{
				if (m_PagePermissionFilter != k_GuestPageFilter)
				{
					Response.Redirect("~/Login.aspx");
				}
			}

			else
			{
				if ((LoggedInUser.UserPermissions & m_PagePermissionFilter) != m_PagePermissionFilter)
				{
					Response.Redirect("~/PermissionError.aspx");
				}
			}

		}

		protected void Page_Load(object sender, EventArgs e)
		{
			StringBuilder sb = new StringBuilder();
			StringWriter sw = new StringWriter(sb);
			HtmlTextWriter tw = new HtmlTextWriter(sw);
			TitleContentPlaceHolder.RenderControl(tw);
			Page.Title = sb.ToString();

			string loggedInUserEmail = (LoggedInUser == null)? "Guest": LoggedInUser.Email;
			helloMessage.Text = string.Format("Hello {0}", loggedInUserEmail);

			if (!showHeader)
			{
				HeaderPanel.Visible = false;
				Body.Attributes.Add("class", "NoHeaderBody");
			}

			checkPermissionFilter();
		}

		protected void Page_Prerender(object sender, EventArgs e)
		{
			if (this.Page.ToString() == "ASP.login_aspx")
			{
				Bredcrumbs.Visible = false;
			}
		}


	}
}